<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model('login_model');
		$this->load->library(array('session','form_validation'));
		$this->load->helper(array('url','form'));
		$this->load->database('default');
		$this->load->model('Usuarios_model','',TRUE);		
	}

	public function index()
	{
		$controlador = "admin";
		switch ($this->session->userdata('id_role')) {
			case '':
				$data['token'] = $this->token();
				$data['titulo'] = 'Login';
				$this->load->view('login_view', $data);
				break;
			case '1':
				redirect(base_url().$controlador);
				break;
			case '2':
				redirect(base_url().$controlador);
				break;
			case '3':
				redirect(base_url().$controlador);
				break;
			default:
				$data['token'] = $this->token();
				$data['titulo'] = 'Login';
				$this->load->view('login_view', $data);
				break;
		};
	}

	public function token()
	{
		$token = md5(uniqid(rand(),true));
		$this->session->set_userdata('token',$token);
		return $token;
	}

	public function reintentar()
	{
		if($this->input->post('token') && $this->input->post('token') == $this->session->userdata('token'))
		{
				$username = $this->input->post('username');
				$password = sha1($this->input->post('password'));
				$check_user = $this->login_model->login_user($username,$password);
				//print_r($check_user);
				if($check_user == TRUE & $check_user->enable == TRUE)
				{
					$data = array(
				'is_logued_in' => TRUE,
				'id_usuario' =>  $check_user->id,
				'id_role' => $check_user->id_role,
				'username' => $check_user->username
					);
					$this->session->set_userdata($data);
					$this->index();
				}
				else redirect(base_url().'login');
			//}
		}else{
			redirect(base_url().'login');
		}
	}

	public function newUser()
	{
		$this->load->view('register');
	}
	
	
	public function newUserAdd()
	{
		$usuario = array(
				//Información general
				'nombre' 			=> $this->input->post('name'),
				'apellido' 			=> $this->input->post('surname'),
				'documento' 		=> $this->input->post('dni'),
				'fec_nac' 			=> $this->input->post('fechaNacimiento'),
				'direccion' 		=> $this->input->post('direccion'),
				//Información de sesión
				'nombre_usuario' 	=> $this->input->post('usuario'),
				'email' 			=> $this->input->post('email'),
				'password' 			=> $this->input->post('password'),
				'enable'		 	=> $this->input->post('activo'),
				'id_role'		 	=> "2"
		);
		$this->Usuarios_model->save($usuario);
			
		$data['message'] = '<div class="success">El usuario fue dado de alta exitosamente</div>';
		$this->load->view('register');
	}
	
	public function logout_ci()
	{
		$this->session->unset_userdata('is_logued_in');
		$this->session->sess_destroy();
		redirect('login', 'refresh');
	}
}
